﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Slja.Model;
using System.IO;
using System.Web.Script.Serialization;
using Slja.WEB;
using FrameWork.Components;
using Slja.Lib;
using AjaxPro;
using FrameWork;

namespace Slja.WEB.Design
{
    public partial class Content : System.Web.UI.Page
    {
        string _id,_year,_region, _shop, _prjId,_prjName;
        /// <summary>
        /// 是否可编辑
        /// </summary>
        public bool Editable
        {
            get
            {
                if (ViewState["Editable"] == null)
                {
                    ViewState["Editable"] = false;
                }
                return (bool)ViewState["Editable"]; 
            }
            set { ViewState["Editable"] = value; }
        }
        /// <summary>
        /// 是否可删除
        /// </summary>
        public bool Deletable
        {
            get
            {
                if (ViewState["Deletable"] == null)
                {
                    ViewState["Deletable"] = false;
                }
                return (bool)ViewState["Deletable"];
            }
            set { ViewState["Deletable"] = value; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //Page.ClientScript.RegisterStartupScript(this.GetType(), "Msg", "window.parent.changewin();", true);
            AjaxPro.Utility.RegisterTypeForAjax(typeof(Content)); 

            string[] sate = { "是", "否" };
            //if (!SessionBox.CheckUserSession())
            //{
            //    Response.Redirect("~/Login.aspx");
            //}
            //else
            //{
            //    UserHandle.InitModule("Design_PrjStatistical");//初始化模块权限
            //}
            
            if (!IsPostBack)
            {               
                //Editable = UserHandle.ValidationHandle(RGP_Tag.Edit);
                //Deletable = UserHandle.ValidationHandle(RGP_Tag.Delete);
                Editable = FrameWorkPermission.CheckPermission(PopedomType.Edit);
                Deletable = FrameWorkPermission.CheckPermission(PopedomType.Delete);
                _id = Request.QueryString["id"];
                _region = Request.QueryString["region"];
                _shop = Request.QueryString["shop"];
                _prjId = Request.QueryString["prjid"];
                _prjName = Request.QueryString["prjname"] == null ? "" : Request.QueryString["prjname"];
                _year = Request.QueryString["year"];
                if (_id != "0")
                {                   
                    LoadMode(int.Parse(_id));

                }
                else
                {
                    btnEdit.Visible = false;
                    btnSave.Visible = true;
                    btnDel.Visible = false;

                    hdfID.Value = _id;
                    tbxRegion.Text = _region == "0" ? "" : _region;
                    tbxShop.Text = _shop == "0" ? "" : _shop;
                    tbxPrjName.Text = _prjName;
                    tbxPrjID.Text = _prjId == "0" ? "" : _prjId;
                    tbxDate.Text = _year + "-";
                    plhFilePack.Visible = false;
                    
                }                
            }
        }
        private void LoadMode(int mID)
        {
            Slja.BLL.PrjDesign bll = new Slja.BLL.PrjDesign();
            PrjMain mModel = bll.GetModel(mID);
     
            if (mModel == null)
            {
                //Response.Write("对不起！数据不存在！");
                ClientScript.RegisterStartupScript(typeof(Page), "warning", "alert('对不起！数据不存在！');", true);
                return;
            }
            hdfID.Value = mModel.ID.ToString();
            tbxRegion.Text = mModel.Region ;
            tbxShop.Text = mModel.Shop;
            tbxPrjName.Text = mModel.PrjName;
            tbxPrjID.Text = mModel.PrjID;
            tbxDate.Text = mModel.DesignDate;
            tbxDesigner.Text = mModel.Designer;
            
            if (mModel.PrjDesignDetails != null && mModel.PrjDesignDetails.Count > 0)
            {
                MainDTableHdf.Value =HttpUtility.HtmlDecode(mModel.PrjDesignDetails[0].DesignXml);
               // hdfImgPath.Value = mModel.PrjDesignDetails[0].ImgPath;
                imgView.Attributes["src"] = mModel.PrjDesignDetails[0].ImgPath;
                hdfImgData .Value= mModel.PrjDesignDetails[0].ImgPath;
            }
            //绑定文件包
            plhFilePack.Visible = true;
            BindFilepack();

            //绑定明细
            btnEdit.Visible = true;
            btnSave.Visible = false;
            btnDel.Visible = true;
            
        }
        protected void btnSave_click(object sender, EventArgs e)
        {
            if (!FormValid()) { return; }
            if(hdfID.Value == "0")
            {

                Slja.BLL.PrjDesign bll = new Slja.BLL.PrjDesign();
                if(bll.Exist(tbxPrjID.Text.Trim()))
                {
                    JScript.MsgBox(Page, "此ID号已经存在，不能新增");
                    return;
                }
                //处理记录信息
                PrjMain mModel = new Slja.Model.PrjMain();
                mModel.DesignDate = tbxDate.Text.Trim();
                mModel.Designer = tbxDesigner.Text.Trim();
                //mModel.ID = int.Parse(hdfID.Value);
                mModel.PrjID = tbxPrjID.Text.Trim();
                mModel.PrjName = tbxPrjName.Text.Trim();
                mModel.Region = tbxRegion.Text.Trim();
                mModel.Shop = tbxShop.Text.Trim();
                mModel.PrjDesignDetails = new List<Slja.Model.PrjDesignDetail>();
                PrjDesignDetail dModel = new PrjDesignDetail();                
                dModel.DesignXml = HttpUtility.HtmlEncode(MainDTableHdf.Value);
                dModel.ImgPath = PrepareImgPath();//处理图片
                
                
                mModel.PrjDesignDetails.Add(dModel);

              
                int mID = bll.Add(mModel);
                hdfID.Value = mID.ToString();

                LoadMode(int.Parse(hdfID.Value));
                
                //ClientScript.RegisterStartupScript(typeof(Page), "Add", "alert('新增成功！');", true);
                JScript.MsgBox(Page, "新增成功");
            }
        }
        string SaveImg(HttpPostedFile hpf,string localPath,string idx)
        {
            string strOldFilePath = localPath;
            //取得上传文件的扩展名
            string strExt = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
            string vPath = "/UpLoadFile/Design/" + tbxRegion.Text + @"/" + tbxShop.Text + "(" + tbxPrjID.Text + ")_" + idx + strExt;
            string CreatePath = Server.MapPath("/") + "/UpLoadFile/Design/" + tbxRegion.Text + "/";
            string FullPath = Server.MapPath("/") + vPath;
            if (!Directory.Exists(CreatePath))
            {
                Directory.CreateDirectory(CreatePath);
            }
            hpf.SaveAs(FullPath);
            return vPath;
        }
        string PrepareImgPath()
        {
            string str = "";
            string strSource = hdfImgData.Value;
            System.Web.Script.Serialization.JavaScriptSerializer serializer 
                = new System.Web.Script.Serialization.JavaScriptSerializer();
            object[] Arr = (object[])serializer.DeserializeObject(strSource);
            //Dictionary<string, object>[] newArr = new Dictionary<string, object>[Arr.Length];
         
           
             if(Request.Files.Count>0)
            {
                //HttpPostedFile 
                Object postedFile = Request.Files;
            }            
            string vPath= "";
            int j = 0;
            List<IDictionary<string, object>> list = new List<IDictionary<string, object>>();
            for (int i = Arr.Length-1; i >=0 ; i--)
            {
                Dictionary<string, object> dict = (Dictionary<string, object>)Arr[i];
                if (dict != null)
                {
                    if (j < Request.Files.Count && dict["status"].ToString() == "2")
                    {

                        //保存图片，并返回
                        vPath = SaveImg(Request.Files[j], dict["path"].ToString(), dict["idx"].ToString());
                        dict["path"] = vPath;
                        dict["status"] = "1";
                        // newArr[i] = Arr[i];
                        dict["idx"] = list.Count;
                        list.Add(dict);
                        j++;

                    }
                    else if (dict["status"].ToString() == "3")
                    {
                        string fullPath = Server.MapPath(dict["path"].ToString());
                        if (File.Exists(fullPath))
                        {
                            File.Delete(fullPath);
                        }
                        //Arr[i] = null;
                    }
                    else if (dict["status"].ToString() == "1")
                    {
                        dict["idx"] = list.Count;
                        list.Add(dict);
                    }
                }
            }
            str = serializer.Serialize(list);
            return str;
        }
        protected void btnEdit_click(object sender, EventArgs e)
        {
            if (!FormValid()) { return; }
            if (hdfID.Value != "0")
            {
                //处理附件
                string vPath = hdfImgPath.Value;               
                PrjMain mModel = new Slja.Model.PrjMain();
                mModel.DesignDate = tbxDate.Text.Trim();
                mModel.Designer = tbxDesigner.Text.Trim();
                mModel.ID = int.Parse(hdfID.Value);
                mModel.PrjID = tbxPrjID.Text;
                mModel.PrjName = tbxPrjName.Text;
                mModel.Region = tbxRegion.Text;
                mModel.Shop = tbxShop.Text;
                mModel.PrjDesignDetails = new List<Slja.Model.PrjDesignDetail>();
                PrjDesignDetail dModel = new PrjDesignDetail();
                dModel.PID = mModel.ID;
                dModel.DesignXml = HttpUtility.HtmlEncode(MainDTableHdf.Value);
                dModel.ImgPath = PrepareImgPath();  //处理图片
                
                mModel.PrjDesignDetails.Add(dModel);

                Slja.BLL.PrjDesign bll = new Slja.BLL.PrjDesign();
                bll.Update(mModel);

                LoadMode(int.Parse(hdfID.Value));
                ClientScript.RegisterStartupScript(typeof(Page), "Edit", "alert('保存成功！');", true);
                
            }

        }

        protected void btnDel_click(object sender, EventArgs e)
        {
            if (hdfID.Value != "")
            {
                Slja.BLL.PrjDesign bll = new Slja.BLL.PrjDesign();
                bll.Delete(int.Parse(hdfID.Value));

                ClientScript.RegisterStartupScript(typeof(Page), "Edit",
                @"alert('删除成功！');parent.fraTree.location.href+='';var l=window.location.href;window.location.href=l.replace(/id=\w+/,'id=0');
                ", true);

            }
        }
        private bool FormValid()
        {
            if (tbxRegion.Text.Trim() == "")
            {
                JScript.MsgBox(Page, "请输入区域");
                return false;
            }
            if (tbxShop.Text.Trim() == "")
            {
                JScript.MsgBox(Page, "请输入店名");
                return false;
            }
            if (tbxPrjID.Text.Trim() == "")
            {
                JScript.MsgBox(Page, "请输入ID号");
                return false;
            }
            if (!Slja.Lib.VerifyData.IsDate(tbxDate.Text.Trim()))
            {
                JScript.MsgBox(Page, "日期格式不正确");
                return false;
            }
            return true;
        }
        protected override void OnPreRender(EventArgs e)
        {
            if (!Editable)
            {
                btnDel.Visible = false;
                btnEdit.Visible = false;
                btnSave.Visible = false;
            }else if (!Deletable)
            {
                btnDel.Visible = false;
            }
            base.OnPreRender(e);
        }
        private void BindFilepack()
        {
            if (hdfID.Value != "")
            {
                BLL.PrjDesignFilepack fp = new BLL.PrjDesignFilepack();

                List<Slja.Model.PrjDesignFilepack> list = fp.GetModelListByPrj(int.Parse(hdfID.Value));
                RepeaterFilepacks.DataSource = list;
                RepeaterFilepacks.DataBind();
            }
        }
        [AjaxMethod]
        public static List<Model.PrjDesignFilepack> GetFilepackList(int id)
        {
            BLL.PrjDesignFilepack fp = new BLL.PrjDesignFilepack();
            List<Model.PrjDesignFilepack> list = fp.GetModelListByPrj(id);
            //string json = Newtonsoft.Json.JsonConvert.SerializeObject(list);
            return list;
        }
    }
}